package com.gitee.cirnochat.common.event.listener;

import com.gitee.cirnochat.common.event.DeviceOfflineEvent;
import com.gitee.cirnochat.common.model.dto.NoticeMessage;
import com.gitee.cirnochat.common.model.dto.payload.DeviceOfflinePayload;
import com.gitee.cirnochat.common.model.enums.SystemNoticeType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import static com.gitee.cirnochat.common.constant.RedisKey.ACCESS_TOKEN_KEY;
import static com.gitee.cirnochat.common.constant.RedisKey.REFRESH_TOKEN_KEY;
import static com.gitee.cirnochat.common.constant.WebSocketConstant.CHAT_SYSTEM_CHANNEL;

@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceOfflineListener {

    private final SimpMessagingTemplate simpMessagingTemplate;
    private final StringRedisTemplate redisTemplate;

    @EventListener(classes = DeviceOfflineEvent.class)
    public void handleDeviceOffline(DeviceOfflineEvent event) {
        log.info("用户{}的设备{}({})已被强制下线", event.getUserId(), event.getDeviceId(), event.getDeviceType());
        NoticeMessage<DeviceOfflinePayload> noticeMessage = new NoticeMessage<>();
        DeviceOfflinePayload deviceOfflinePayload = new DeviceOfflinePayload();
        deviceOfflinePayload.setDeviceId(event.getDeviceId());
        deviceOfflinePayload.setDeviceName(event.getDeviceName());
        deviceOfflinePayload.setDeviceType(event.getDeviceType());
        deviceOfflinePayload.setOfflineTime(System.currentTimeMillis());
        noticeMessage.setPayload(deviceOfflinePayload);
        noticeMessage.setType(SystemNoticeType.DEVICE_OFFLINE_NOTICE);
        // 清除AK和SK
        // 删除 accessToken redis key
        redisTemplate.delete(ACCESS_TOKEN_KEY + String.format("%s#%s", event.getDeviceId(),  event.getUserId()));
        // 删除 refreshToken redis key
        redisTemplate.delete(REFRESH_TOKEN_KEY + String.format("%s#%s", event.getDeviceId(),  event.getUserId()));
        simpMessagingTemplate.convertAndSendToUser(
                event.getUserId().toString(),
                CHAT_SYSTEM_CHANNEL,
                noticeMessage
        );
    }
}